package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizErrorCode;
import com.atguigu.common.utils.R;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

@RestControllerAdvice
public class GulimallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerValidException(MethodArgumentNotValidException exception) {
        if (exception.getBindingResult().hasErrors()) {
            HashMap<String, String> errInfo = new HashMap<>();
            exception.getBindingResult().getFieldErrors().forEach(e -> errInfo.put(e.getField(), e.getDefaultMessage()));
            return R.error(BizErrorCode.VALID_ERROR).put("data", errInfo);
        }
        return R.error(BizErrorCode.VALID_ERROR);
    }

    //    @ExceptionHandler(value = Exception.class)
    public R handlerGlobalException(Exception exception) {
        return R.error(BizErrorCode.INTERNAL_ERROR).put("data", exception.getMessage());
    }
}
